'''
Created on 2011-08-14

@author: Nich
'''
import tornado.ioloop
import os.path
from tornado.options import options, parse_command_line
from PyMud.network.chatserver import MainHandler, AuthLoginHandler, AuthLogoutHandler, MessageUpdatesHandler, CommandMessageHandler, CharacterSelectHandler, CharacterCreateHandler
from PyMud.command.command_handler import CommandHandler
from PyMud.command.command_token_matcher import CommandTokenMatcher
from PyMud.command.command_packager import CommandPackager
from PyMud.command.command_executor import CommandExecutor
from PyMud.command.command_context_builder import CommandContextBuilder
from PyMud.command.commands import verbs
from PyMud.player.avatar import AvatarFactory
from PyMud.player.player import PlayerFactory
from PyMud.objects.component_manager import ComponentManager, DBComponentSource, ArrayComponentSource

from PyMud.objects.node_factory import NodeFactoryDB


from PyMud.model.account import AccountUtils
import PyMud.model.base as base


from PyMud.Systems.AnnoyingTickSystem import AnnoyingTickSystem
from PyMud.Systems.NetworkMessageSystem import NetworkMessageSystem
from PyMud.Systems.network_av_system import NetworkAVSystem
from PyMud.Systems.messanger import start_queue_process, MessagePassingModule

from PyMud.objects.components import components
from PyMud.room.room_components import components as room_components

all_components = {}
all_components.update(components)
all_components.update(room_components)


db_engine = base.engine('sqlite:///main.db')
Session = base.create_sessionmaker(db_engine)
base.Base.metadata.create_all(db_engine)



object_db = DBComponentSource(all_components)

component_manager = ComponentManager([object_db])
node_factory = NodeFactoryDB(component_manager, Session)
#_, gryffindore_common_room, gcr_n, chair1, chair2 = create_test_room(component_manager)

player_factory = PlayerFactory(component_manager)
#default_player = player_factory.create_player(MessageBuffer(), pid = "https://www.google.com/accounts/o8/id?id=AItOawlkarxOCYQft08wF56m2ahXKULVMJYatFQ")

default_room = ""

avatar_factory = AvatarFactory(node_factory, component_manager, {
                                               "starting_room":default_room,
                                               "player_id":0,
                                               
                                               
                                               })


account_utils = AccountUtils(Session, avatar_factory)





#default_avatar = avatar_factory.create_default_avatar()


#default_player.set_avatar(default_avatar)




command_token_matcher = CommandTokenMatcher()
command_packager = CommandPackager(verbs)

command_context_builder = CommandContextBuilder(node_factory)



from multiprocessing import Queue
network_players = {}


mpm = MessagePassingModule(Queue()) 
ats = AnnoyingTickSystem(mpm.queue, node_factory)
nms = NetworkMessageSystem(node_factory, player_factory, Session)

#default_player_network_node = node_factory.create_node(default_avatar.id, ["senses", "location"])



nAVs = NetworkAVSystem(Queue(), node_factory, mpm.queue)


mpm.register_handler("NetworkMessage", nms.network_message_queue)
mpm.register_handler("AVMessage", nAVs.av_message_queue)

command_executor = CommandExecutor(mpm)
command_handler = CommandHandler(command_token_matcher, command_packager, command_executor, command_context_builder)





def main():
    parse_command_line()
    
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/auth/login", AuthLoginHandler, dict(account_utils = account_utils, player_factory = player_factory)),
            (r"/auth/logout", AuthLogoutHandler),
            (r"/a/message/new", CommandMessageHandler, dict(command_handler = command_handler, player_factory = player_factory)),
            (r"/a/message/updates", MessageUpdatesHandler, dict(player_factory = player_factory)),
            (r"/character_select", CharacterSelectHandler, dict(account_utils = account_utils, player_factory = player_factory)),
            (r"/character_create", CharacterCreateHandler, dict(account_utils = account_utils, player_factory = player_factory)),
            ],
        cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
        login_url="/auth/login",
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        xsrf_cookies=True,
        )
    app.listen(options.port)
    annoying_tick_callback = tornado.ioloop.PeriodicCallback(ats.send_annoying_tick, 5000, io_loop=tornado.ioloop.IOLoop.instance())
    network_message_system_callback = tornado.ioloop.PeriodicCallback(nms.handle_network_messages, 100, io_loop=tornado.ioloop.IOLoop.instance())
    network_av_system_callback = tornado.ioloop.PeriodicCallback(nAVs.process_AV_messages, 100, io_loop=tornado.ioloop.IOLoop.instance())
    
    annoying_tick_callback.start()
    network_message_system_callback.start()
    network_av_system_callback.start()
    
    start_queue_process(mpm.queue, mpm.handler_dict)
    
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()